/*
 * @Author: your name
 * @Date: 2021-12-17 15:31:19
 * @LastEditTime: 2023-04-20 10:40:28
 * @LastEditors: 陈宇 975155172@qq.com
 * @Description: 文章相关 接口方法 （增 删 改 查）
 * @FilePath: \blog-api\src\user\user.service.ts
 */
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository, InjectEntityManager } from '@nestjs/typeorm';
import { Repository, Like, EntityManager, In } from 'typeorm';
import { AbstractDto } from './dto/create-post.dot';
import { Abstract } from './entities/abstract.entity';
import { Abstract as AbstractApi } from './abstract';

import { Tags } from '../tags/entities/tags.entity';
import { TagsService } from '../tags/tags.service';
import { Categories } from '../categories/entities/categories.entity';
import { CategoriesService } from './../categories/categories.service';


@Injectable()
export class AbstractService {
  // 使用InjectRepository装饰器并引入Repository这样就可以使用typeorm的操作了
  constructor(
    @InjectRepository(Abstract)
    private readonly abstractRepository: Repository<Abstract>,
		private readonly abstract: AbstractApi,

    private tagsService: TagsService,
    private categoriesService: CategoriesService,

    @InjectEntityManager() private entityManager: EntityManager,
  ) {}

  // 获取文章列表
  async list(body: any): Promise<AbstractDto> {
		const querySQL = {
			where: {
				title: Like(`%${ body.title ? body.title : '' }%`),
				categories: Like(`%${ body.categories ? body.categories : '' }%`),
				tags: Like(`%${ body.tags ? body.tags : '' }%`),
			}
		}
		const [ abstractList, abstractTotal ] = await this.abstractRepository.findAndCount({
			take: body.page_count,
			skip: (body.page - 1) * body.page_count,
			order: {
        id: "DESC"
			},
			join: {
				alias: 'tags'
			},
      relations: ['category', 'tag'],
			...querySQL,
		});

    return {
      list: abstractList,
      total: abstractTotal,
      page: body.page,
      pageCount: Math.ceil(abstractTotal / body.page_count),
      pageSize: body.page_count,
    };
  }

  // 获取文章详情
  async details(body: any): Promise<any> {
    const abstractDetails = await this.abstractRepository.findOne({
      where: {
        id: body.id,
      },
      relations: ['category', 'tag'],
    });
    return abstractDetails;
  }

  // 点赞
  async addPraise(body: any): Promise<any> {
    const article = await this.abstractRepository.findOne({
      where: {
        id: body.id,
      }
    });

    article.praise++;
    await this.abstractRepository.save(article); // 保存更改

    return {
      message: "增加成功"
    }
  }

  // 增加查看次数
  async addSeeNum(body: any): Promise<any> {
    const article = await this.abstractRepository.findOne({
      where: {
        id: body.id,
      }
    });

    article.see_num++;
    await this.abstractRepository.save(article); // 保存更改

    return {
      message: "增加成功"
    }
  }

  // 文章显示状态修改
  async articleShow(body: any): Promise<any> {
    await this.abstractRepository.update(body.id, { is_show: body.isShow });
    return {
      message: '文章显示状态修改成功'
    };
  }

  // 删除文章
  async removeArticle(body: any): Promise<any> {
    // await this.abstractRepository.delete(body.id);
		await this.abstractRepository.update(body.id, { is_delete: true });

    return {
      message: '文章删除成功'
    };
  }

  // 添加文章
  async addArticle(body: any): Promise<any> {
    const tags = await this.tagsService.queryTags({ids: body.tag});
    const categories = await this.categoriesService.queryCategories({ids: body.category});

    let article: any;
		const setData = {
			title: body.title,
			content: body.content,
			categories: body.categories,
			tags: body.tags,
			describe_content: body.describe_content,
			author: '宇',
		}

    const association = {
      tag: tags,
      category: categories,
    }
    article = await this.abstractRepository.create({ ... setData, ...association });
    await this.abstractRepository.save(article);
    await this.categoriesService.addAbstractNum({ids: body.category});

    return {
      message: '文章创建成功'
    };
  }

  // 修改文章事务
  async updateArticleTransaction(body: any): Promise<any> {
    return this.entityManager.transaction(async transactionalEntityManager => {
      const article = await transactionalEntityManager.findOne(Abstract, {
        where: {
          id: body.id
        }
      });

      if (!article) {
        throw new NotFoundException('Article not found');
      }

      article.title = body.title;
      article.content = body.content;
      article.categories = body.categories;
      article.tags = body.tags;
      article.describe_content = body.describe_content;
      article.author = '宇';

      article.category = await transactionalEntityManager.findBy(Categories, {
        id: In(body.category)
      })
      article.tag = await transactionalEntityManager.findBy(Tags, {
        id: In(body.tag)
      })

      const abstractDetails = await this.details(body);
      await this.categoriesService.addAbstractNum({ids: body.category});
      await this.categoriesService.reduceAbstractNum({ids: abstractDetails.category_id});

      // 保存更改
      await transactionalEntityManager.save(Abstract, article);

      // 你可以在这里添加更多的数据库操作，它们都将在同一个事务中执行

      return {
        message: '文章修改成功'
      };
    });
  }
}
